package com.societyGames.codeAlong.state.codeExercise.view
{
import com.societyGames.flashForms.basicSkin.SharedTextFields;

import flash.events.FocusEvent;
import flash.events.TextEvent;
import flash.text.AntiAliasType;
import flash.text.GridFitType;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;

public class CodeTextField extends TextField
	{	
		public function CodeTextField()
		{
			var textFormat:TextFormat = new TextFormat();
			textFormat.font = "Inconsolata";
			textFormat.size = SharedTextFields.TEXT_LARGE_SIZE;
			textFormat.color = 0x000000;
			this.defaultTextFormat = textFormat;
			
			this.type = TextFieldType.INPUT;
			this.multiline = true;
			this.selectable = true;
			this.embedFonts = true;
			this.antiAliasType = AntiAliasType.ADVANCED;
			this.gridFitType = GridFitType.PIXEL;
			this.useRichTextClipboard = true;
			
			this.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, codeTextFieldKeyFocusChange);
			this.addEventListener(TextEvent.TEXT_INPUT, textInputHandler);
		}
		
		private function textInputHandler(event:TextEvent):void
		{
			if (event.text.length > 1)
			{
				event.preventDefault();
				var textField:TextField = TextField(event.target);
				var currentText:String = textField.text; 
				var insertionPrefix:String = currentText.substr(0, textField.selectionBeginIndex); 
				var insertionSuffix:String = currentText.substr(textField.selectionEndIndex, currentText.length); 
				var startIndex:int = textField.selectionBeginIndex;
				textField.text = insertionPrefix + event.text + insertionSuffix; 
				textField.setSelection(startIndex + event.text.length, startIndex + event.text.length); 
			}
		}
		
		public function showErrorAt(lineIndex:int):void
		{
			//Make sure to focus on ourselves to make the selection work.
			this.stage.focus = this;
			//
			this.scrollH = 0;
			this.scrollV = lineIndex + 1; //The line index is 0 based, but he scrollV is 1 based.
			//Show the error here.
      if (lineIndex >= 0 && lineIndex < this.numLines) //TODO: If the error is outside user text... adjust the line number?
			{
				var characterIndex:int = this.getLineOffset(lineIndex);
				var lineLength:int = this.getLineLength(lineIndex);
				this.setSelection(characterIndex, characterIndex + lineLength);
			}
		}
		
		private function codeTextFieldKeyFocusChange(event:FocusEvent):void
		{
			event.preventDefault();
			this.text = this.text.slice(0, this.caretIndex) + "\t" + this.text.slice(this.caretIndex, this.text.length);
			this.setSelection(this.caretIndex + 1, this.caretIndex + 1);
		}
	}
}
